
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
include "header.php";
$page = "create_transaction";

//check user login
if (!$user->user_exists) {
    header('Location: ./login.php');
    exit();
}
if ($user->user_info['type_id'] != 1) {
    header('Location: ./restrict.php');
    exit();
}
$code = null;
$contract = array();
$errors = array();
$search = false;
$transaction = new Transaction();
$submit = false;

if (isset($_POST['code'])) {
    $code = $_POST['code'];
} elseif (isset($_GET['code'])) {
    $code = $_GET['code'];
}
if (isset($_POST['content_id'])) {
    $content_id = $_POST['content_id'];
} elseif (isset($_GET['content_id'])) {
    $content_id = $_GET['content_id'];
}else{
    $content_id = null;
}

if (isset($_POST['repair_id'])) {
    $repair_id = $_POST['repair_id'];
} elseif (isset($_GET['repair_id'])) {
    $repair_id = $_GET['repair_id'];
}else{
    $repair_id = null;
}

if(isset($_POST['search']) && !empty($_POST['search'])){
    $search = true;
    if(empty($code)){
        $errors['Code'] = "Please complete this field - it is required.";
    }
    if(empty($errors)){
        $contract = $transaction->getContract($code);
    }
}
if(isset($_POST['submit']) && !empty($_POST['submit'])){
    $submit = true;
    if(empty($code)){
        $errors['Code'] = "Please complete this field - it is required.";
    }
    $contract = $transaction->getContract($code);
    if(empty($repair_id)){
        $errors['Repair Company'] = "Please complete this field - it is required.";
    }
    if(empty($content_id)){
        $errors['Content'] = "Please complete this field - it is required.";
    }
    if(empty($errors)){
        $transaction_id = $transaction->createTransaction($code, $repair_id, $content_id);
        header("Location: edit_transaction.php?id=$transaction_id"); 
    }
}
$smarty->assign("repair_users", $transaction->getRepairUsers());
$smarty->assign("contents", $transaction->getContents());
$smarty->assign('code', $code);
$smarty->assign('content_id', $content_id);
$smarty->assign('repair_id', $repair_id);
$smarty->assign('contract', $contract);
$smarty->assign('search', $search);
$smarty->assign('submit', $submit);
$smarty->assign('errors', $errors);

include "footer.php";